# -*- coding: utf-8 -*-
import scrapy
import time
import copy
import json
import requests

class TiWatchSpider(scrapy.Spider):
    name = 'ti_watch'
    allowed_domains = ['www.ti.com.cn']
    start_urls = ['https://www.ti.com.cn/']

    custom_settings = {
        'DEFAULT_REQUEST_HEADERS': {
            'Connection': 'keep-alive',
            'Pragma': 'no-cache',
            'Cache-Control': 'no-cache',
            'sec-ch-ua': '" Not;A Brand";v="99", "Google Chrome";v="91", "Chromium";v="91"',
            'sec-ch-ua-mobile': '?0',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36',
            'Accept': '*/*',
            'Sec-Fetch-Site': 'same-origin',
            'Sec-Fetch-Mode': 'cors',
            'Sec-Fetch-Dest': 'empty',
            'Referer': 'https://www.ti.com.cn/sitesearch/docs/universalsearch.tsp?langPref=zh-CN&searchTerm=TPS22918TDBVRQ1&nr=20',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Cookie': 'user_pref_language="zh-CN"; CONSENTMGR=ts:1623161593440%7Cconsent:true; tiSessionID=0179ebf85e620004d1c6bcffcfa30306d004706500bd0; _ga=GA1.3.2008814937.1623161640; seerid=u_857154021832726700; da_lid=CE140C499A72EA22847BBB990FBFC87161|0|0|0; _fbp=fb.2.1623161737328.1439528132; _sg_b_v=1%3B0%3B1623161741; _sg_b_n=1623161741195; ELOQUA=GUID=A45DD67939904CC7B58723BA202DB973; ti_ua=Mozilla%2f5.0%20(Windows%20NT%2010.0%3b%20WOW64)%20AppleWebKit%2f537.36%20(KHTML,%20like%20Gecko)%20Chrome%2f91.0.4472.77%20Safari%2f537.36; ti_bm=; user_pref_givenName="z"; ti_get_lit=ts%3D1623241071267%7Clit%3DQuick%2520add%2520to%2520cart%2520template.xlsx%7Cpid%3D%7Caid%3D%7Cgpn%3DNon-Product%7Cpt%3Dstore%7Cevt%3D202159201751267%7C; __adroll_fpc=aa558a8ff5322e90046aa4d0981b9b6a-1623241145173; login-check=null; alias=homepageproduct; acceleratorSecureGUID=4d64e1a0b489115b5b764a11a1a60ea090c26a43; login-check=null; user_pref_shipTo="AL"; user_pref_currency="USD"; auth_session=eyJhbGciOiAiZGlyIiwgImVuYyI6ICJBMjU2R0NNIn0..WR8grdOFM5ffUa8X.j_kdN-E7_PTlsIfwO_laTUErea2RYUOUqJYDpLhiBOsS1JZuHlHe0qFIDSMqIQa4nZ7ciGhuDMUP3j1bRdZrln52Keeh8MXSE0z0FRbHfshBbWpjW86qWyDZmuNwSPwS4HeI-0yA5t5NXp3gtFANNKS7X6MtgrlQZxq7xwzwgsGuFwQDVRPA1pUhf1RIUx4Lu9mUNNttZSLpfh6RyIVQxTJeYFXm_fc0auoZZ4ObEnxpNsvgPVWYYnxI0L86DhetfKYtZtTstT8OW1wH13p81jXpgHY7lroQ6zSYS9e_RVcHBqogvpIaD875q1rBTzH-pq4Y2ggyrbcczVdqAurObNpvq9glADWxjsn8w2yUSj5VyvmOXh8icW8UC8MFSyVxLEBS_jpoIAlgWkW2UubkIASV5ehTAxC2fG9mrniZS22cGKAXowKaOpelC5wzCaVfsCJYndyFE6fGk2_92TZJ2dJ2ZDTSzBQ9f6t375_owOLm5tZOXeehHQgO3DJoJxVMx3gCvQ9yPAK_B4K1eyOUsC_RkEm9DewZlQ0DZy1DZLymu1KjfaEow-cn-A8MzF048-zdfVAeJYAvrDIxD3GXuS6Igo-x87AvB3OSh30RLx361HYQ7zsK9rcmXOT_WcS_OMB8ZTuTkDq2LCKv0fw2PHG81IWWIlq7PN2JQsf6cwxnOCofuUCQOtDBqHiqcBHg-IPyUkMuUjRyYlOADuRlN4iGf0Cc58ei0SXnvcSs_xwuYQH-svP3MIhCGSUXn_8GptkZ-WAT4869tINRt4z31CuJvgS6n7-9gY4Q_YxcjC7wydBnQdZfQ33aRt-HJ_t_VY9YupHAeXu5VmiBfIIo9dpJoGm5vAGa4wzJjwyPjxJDs5Rj_5v5mtnPFEZy4u-CEeEUYgXavvV5Vdss45p3zMD2BOKNk62Nldvhr2aYG7mdVPTIq6hq4fFcP9J2bAq7roYTwnWpBur2koNKtGrXjl2R3AsmiBLguw8ft2NJR1W-kIBkFgckg9S0wTuFTwz-w20numVmiYawlXFKVRsWt-zdbTjkJYNonj23izi6X10y4AfuuJjdYroTV2rinGZ9dGveeD8mCyNM_0dgpT_Ctne08AdWk_k_iHMy9NiZs_hIMIXWT4Plj_4guBwvlXMITowexOqTX_MLTQsimUdtTmoDzsCUSS7od6g6_ehQENr4NsCTEo5HbBv42cV4xu8irIs9ytL8qalXhp99hkIrQKyLc-ALKt7FzoLybAB2-ASMGYD8HePUb_5oXr_FY6iA2DTMKbtz9gi5_HVr8surb0BjmS2DkOCAf4mcf2UxGcVvV3cHLAZNlKxGmEwqCro9h3gnO45UKNM_5YsO6r3cDm5krwQ_wZUizn24LXTBrtsX8rGBJTzLQlKnv3nvTnvgK2A_b8PD6DjhtrTO4XgELAuaitLFvhc3IKZ9-8CkAKu3gsevE_mbhM6nHbBu6LjJ4vAfWO8TE80FQSVdT28y71LVVlYUXInUIaq9HULWuhNJRldtss3-dYtxtKw-PdIRhUM5mJAcHYbAdvbwk5i3NUKgQSPy_SwfLqSPg6IcjgvBXlw3XjcN7vur-Hzn6P2h7paqGWpQ29Gyt71AVGHlezKcDpRtQEsLmQ.xPDs0bEqECKeLNgvNGfo9Q; user_pref_givenNameLocalLanguage="z"; coveo_visitorId=daf057ea-8964-4f97-b281-9e3231554e03; __ar_v4=G3YHLXUICZC3XKDXYVVLO4%3A20210609%3A17%7C2XNKMR6P4VGD5MD3ZP4SQR%3A20210609%3A17%7CQFXRHQEHOJDMLHSLFIWCLO%3A20210609%3A17; ti_geo=country=CN|city=XIAN|continent=AS|tc_ip=1.80.112.70; _gid=GA1.3.415117657.1623462713; ak_bmsc=5D7C7B659F8DEBAF02A812C32AE860C6~000000000000000000000000000000~YAAQNnfA0pGHq2h5AQAAtxvr/QxkhiQIE6SL/W3Enn3L28nUAztLu66Y1oTlTR4UX8CFqgUE8U2jIp6iyb8L8KoHR/nmj25zhMVaQc4mvDVlRsr88sGO64oBWZLXPWp03iSNSWPN+/H8/8rnjcozZG05Zhdl26ZN8QymWhQixld239GlM89rCn/GsfSyAQ/8K4ZbRqWA4IBqlKDVwjHe6HVSUqja87XY7GwXG3PZUcNKFi32NCm8wZXdGXzh6n8VVmq7OjYJDE4OpFvZICAZz/JL1v6wTgRcu+zmIMGoK9zr5A7eHBlaIhP3NKNZuy+slpulZontgAZ+rmIeNO0G17oLtHgRFzXZvI0xM0Y4/lIKxL62KmBZFpwA9PRX6sQ5UAHTeew3rmoL9PP+3AuSbawDYUYE137SpmrLvT4CNxv1qmjY/YyCgHGNLCee79NFquphtk1qx1urqgnm3PruwF4seBuhpYyt6kFB8mjC; seerses=e; da_sid=8FEE33EB8E3CAE8BA415AA134DA6D21981|4|0|3; da_intState=; tipage=%2Fsitesearch%2Fdocs%2Fsearch%20results%20-%20ti.com; tipageshort=search%20results%20-%20ti.com; ticontent=%2Fsitesearch%2Fdocs; ga_page_cookie=search%20results%20-%20ti.com; ga_content_cookie=%2Fsitesearch%2Fdocs; last-domain=www.ti.com.cn; utag_main=v_id:0179ebf85e620004d1c6bcffcfa30306d004706500bd0$_sn:6$_ss:0$_st:1623465328251$free_trial:false$channel:organic%3Bexp-1625838334727$ctimestamp:Wed%20Jun%2009%202021%2021%3A45%3A34%20GMT%2B0800%20(%E4%B8%AD%E5%9B%BD%E6%A0%87%E5%87%86%E6%97%B6%E9%97%B4)%3Bexp-1625838334727$_pn:6%3Bexp-session$ses_id:1623462712837%3Bexp-session; userType=Anonymous; gpn=Non-Product; ABTasty=uid=ccgkgyrhz36wbb40&fst=1623161642836&pst=1623255708103&cst=1623462713133&ns=5&pvt=63&pvis=6&th=686831.851794.10.10.1.1.1623240731842.1623241371658.NaN; ABTastySession=mrasn=&lp=https%253A%252F%252Fwww.ti.com.cn%252Fsitesearch%252Fcn%252Fdocs%252Funiversalsearch.tsp%253FlangPref%253Dzh-CN%2526searchTerm%253D%2523src%253Dtop%2526linkId%253D1%2526q%253DTPS26600PWPR%2526firstQueryCause%253DsearchFromLink&sen=5; _gat_ga_main_tracker=1; ti_rid=429b79f5; bm_sv=D99629077222C3931F882F51B3D36DE4~hC5ZE2T/RAku6neDpdfpJo+RxCV74sM5dXusT5L6qsyFXoytafKvu7QE0oJrhZ+RK8HVFkAMmUAnLpwfpR06LLqCTpnr6dbasPqULaV8OxvVFKs8QAkwUbbh2HDxVx3e5Z0jBtZ9FRReg+jE27Ppm8wMTOPuX/2QAHVs4mTLeM4=; ti_geo=country=CN|city=XIAN|continent=AS|tc_ip=1.80.112.70; ti_ua=Mozilla%2f5.0%20(Windows%20NT%2010.0%3b%20WOW64)%20AppleWebKit%2f537.36%20(KHTML,%20like%20Gecko)%20Chrome%2f91.0.4472.77%20Safari%2f537.36; ti_bm=; ak_bmsc=14890194E563E076E890E5B270A92F09~000000000000000000000000000000~YAAQNnfA0tOMq2h5AQAA0Lvr/QzoCqw9R5um2XqbhjccvQuePa3DZOE9ZAL7A4tQQbQQMAM4xn2eFH3c2qxQNPPAKN9v80bYfl8A+CZxvMW76TMuOJ0UHjyDtPenwgDAALMhS//RVV9dYdMy3ol9eKAPkJ2jPMZbLRrblxE8xm3c28IVnjG+g+F1L/UEGFwDA6BVfrInQuTSSZGS3gpIDJ1YOmCIkBFUXDQR8evKaIkbf3zhEdvi0fpBnChtY6E50+RxuTmgHJ6LrHuxp2Rwhi75A7EI5xasyAHNksyuNbEk09rzjROARyTrOvg0FMUoW+cxEH057M862th0mEvKMfINCaNjZOlEibeAWP/zx+3b2xt+xs2SnRg=; ti_rid=4bc5ede0; bm_sv=D99629077222C3931F882F51B3D36DE4~hC5ZE2T/RAku6neDpdfpJo+RxCV74sM5dXusT5L6qsyFXoytafKvu7QE0oJrhZ+RK8HVFkAMmUAnLpwfpR06LLqCTpnr6dbasPqULaV8Oxtjane04o2FgM5fbT4ZhQv6Ng57Dsv2Ewc5F0Xt3+5LyUvtoBeChqsdX1gd/qdu0x8='
        },
    }
    
    def __init__(self):
        with open('products.txt') as f:
            self.products = f.read().strip().split('\n')
        super(TiWatchSpider, self).__init__()

    def start_requests(self):
        headers = self.custom_settings.get('DEFAULT_REQUEST_HEADERS')
        self.log("开始监控！")
        # url = "https://www.ti.com.cn/productmodel/TPS27081A/orderables?locale=zh-CN&orderable={}"
        url = "https://www.ti.com.cn/productmodel/{}/tistore?locale=zh-CN"
        for prdt in self.products:
            pid, cid = prdt.split(' ')
            ul = url.format(cid)
            header = copy.deepcopy(headers)
            yield scrapy.Request(ul, callback=self.parse, method='get', headers=header, meta={"cid": cid, "pid": pid},
                                 dont_filter=True)

    def send_ding_ding(self, msg):
        # return
        requests.post(
            'https://oapi.dingtalk.com/robot/send?access_token=c4af75e28c39070ed65a83cbbbf5cf89027543f07c19775486e2f75ff545475d',
            json={
                "msgtype": "text",
                "text": {
                    "content": "[通知] %(msg)s" % {'msg': msg},
                }
            },
            timeout=5
        )

    def parse(self, response):
        meta = response.meta
        cid = meta.get('cid')
        pid = meta.get('pid')
        data = response.text
        data = json.loads(data)
        for dct in data:
            if dct.get('orderablePartNumber') == pid:
                inventory = int(dct.get('inventory'))
                if inventory >= 100:
                    self.log("库存数: {}，准备开始下单！".format(str(inventory)))
                    ltime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                    self.send_ding_ding("时间：{} 商品：{}， 库存数：{}, 地址：https://www.ti.com.cn/store/ti/zh/p/product/?p={}".format(ltime, pid, str(inventory), pid))
                else:
                    url = "https://www.ti.com.cn/productmodel/{}/tistore?locale=zh-CN"
                    ul = url.format(cid)
                    headers = self.custom_settings.get('DEFAULT_REQUEST_HEADERS')
                    header = copy.deepcopy(headers)

                    yield scrapy.Request(ul, callback=self.parse, method='get', headers=header,
                                         meta={"cid": cid, "pid": pid}, dont_filter=True)

